package com.example.common.service.impl;

import com.example.common.mapper.IDataLogMapper;
import com.example.common.mapper.IUserRightMapper;
import com.example.common.pojo.Right;
import com.example.common.pojo.RightList;
import com.example.common.service.IGrantService;
import com.example.right.service.IRightService;
import com.example.util.Constants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import java.util.Iterator;
import java.util.List;

@Service
public class IGrantServiceImpl implements IGrantService {
    private final IUserRightMapper iUserRightMapper;
    private final IDataLogMapper iDataLogMapper;
    private final IRightService iRightService;
    private final DataSourceTransactionManager dataSourceTransactionManager;
    @Autowired
    public IGrantServiceImpl(IRightService iRightService,IUserRightMapper iUserRightMapper,DataSourceTransactionManager dataSourceTransactionManager,IDataLogMapper iDataLogMapper){
        this.iUserRightMapper=iUserRightMapper;
        this.dataSourceTransactionManager=dataSourceTransactionManager;
        this.iRightService=iRightService;
        this.iDataLogMapper=iDataLogMapper;
    }

    @Override
    @Transactional
    public int insertIntoUserRight(Integer id1, Integer id2, RightList rightList) {
        List<Right> rightList1 = rightList.getRightList();
        Iterator<Right> right = rightList1.iterator();
        DefaultTransactionDefinition def=new DefaultTransactionDefinition();
        def.setPropagationBehavior(TransactionDefinition.ISOLATION_REPEATABLE_READ);
        TransactionStatus status = dataSourceTransactionManager.getTransaction(def);

        try{
            while(right.hasNext()){
                this.iUserRightMapper.insertIntoUserRight(id2,right.next().getRightId());
                this.iDataLogMapper.insertDataLog(Constants.INSERT,id1,rightList.toString());
            }
            dataSourceTransactionManager.commit(status);


        }catch (Exception e){
            dataSourceTransactionManager.rollback(status);

            return -1;
        }
    return 1;


    }
}
